﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Top.Data;
using Top.PointStore.Business.Models;

namespace Top.PointStore.Business
{
    public class PointSettingManager
    {
        /// <summary>
        /// 根据行为代码获取积分配置信息
        /// </summary>
        /// <param name="pointCode"></param>
        /// <returns></returns>
        public static async Task<T_PointSetting> Get(string pointCode)
        {
            const string sql = "select * from T_PointSetting where F_PointCode={0} limit 1";
            using (var db = new DbTour())
            {
                return await db.Sql(sql, pointCode).FirstOrDefault<T_PointSetting>();
            }
        }

        public static async Task<T_PointSetting> Get(string pointCode, int buildingKid, DateTime startDate, DateTime endDate, int cityKid)
        {
            StringBuilder sqlStr = new StringBuilder();
            sqlStr.Append("select top 1 * from T_PointSetting where F_Status = 1");

            if (!string.IsNullOrWhiteSpace(pointCode))
            {
                sqlStr.AppendFormat(" and F_PointCode='{0}'", pointCode);
            }

            sqlStr.AppendFormat(" and F_BuildingKid = {0}", buildingKid);
            sqlStr.AppendFormat(" and F_StartTime < '{0}'", startDate);
            sqlStr.AppendFormat(" and F_EndTime > '{0}'", endDate);

            if (cityKid > 0)
            {
                sqlStr.AppendFormat(" and F_CityKid={0}", cityKid);
            }
            sqlStr.Append(" order by F_AddTime desc ");

            using (var db = new DbTour("sqldefault"))
            {
                return await db.Sql(sqlStr.ToString()).FirstOrDefault<T_PointSetting>();
            }
        }

        public static async Task<T_PointSetting> Get(string pointCode, int buildingKid, DateTime startDate, DateTime endDate, int cityKid, DbTour db)
        {
            StringBuilder sqlStr = new StringBuilder();
            sqlStr.Append("select top 1 * from T_PointSetting where F_Status = 1");

            if (!string.IsNullOrWhiteSpace(pointCode))
            {
                sqlStr.AppendFormat(" and F_PointCode='{0}'", pointCode);
            }

            sqlStr.AppendFormat(" and F_BuildingKid = {0}", buildingKid);
            sqlStr.AppendFormat(" and F_StartTime < '{0}'", startDate);
            sqlStr.AppendFormat(" and F_EndTime > '{0}'", endDate);

            if (cityKid > 0)
            {
                sqlStr.AppendFormat(" and F_CityKid={0}", cityKid);
            }
            sqlStr.Append(" order by F_AddTime desc ");


            return await db.Sql(sqlStr.ToString()).FirstOrDefault<T_PointSetting>();

        }
    }
}
